import 'dart:io';
import 'dart:typed_data';

import 'package:baselib/utils/log_util.dart' as LogUtils;
import 'package:baselib/widgets/dialog_util.dart';
import 'package:baselib/widgets/select_photo_camera_alert_widget.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'check_permission_utils.dart';
import 'package:get/get.dart';


class GalleryCameraPickUtil {
  static  ImagePicker _picker = ImagePicker();
  static final GalleryCameraPickUtil _singleton = GalleryCameraPickUtil._internal();

  static GalleryCameraPickUtil get instance => GalleryCameraPickUtil();

  factory GalleryCameraPickUtil() {
    return _singleton;
  }

  GalleryCameraPickUtil._internal() {
    //做一些操作
    if(_picker==null){
      _picker = ImagePicker();
    }
  }

  Future<File> selectPicture({bool isOnlyCamera:false}) async{
    XFile xFile;
    if((isOnlyCamera??false)){
      bool checkPermission =await CheckPermissionUtil.checkCommPermission(Permission.camera);
      if(!checkPermission)return null;
      xFile = await getImageByCamera();
    }else{
      Future<SelectedType> popParams = DialogUtil.instance.showBottomSheet(
          child: SelectPhotoOrCameraAlertWidget());
      // Future<SelectedType> popParams = showModalBottomSheet(
      //     context: context, builder: (_) {
      //   return SelectPhotoOrCameraAlertWidget();
      // });
      SelectedType value = await popParams;
      if (value == SelectedType.SelectedCameraType) {
        bool checkPermission =await CheckPermissionUtil.checkCommPermission(Permission.camera);
        if(!checkPermission)return null;
        xFile = await getImageByCamera();
      } else if (value == SelectedType.SelectedPhotoType) {
        bool checkPermission = false;
        // var request = await Permission.storage.request();
        if(Platform.isIOS){
          checkPermission =await CheckPermissionUtil.checkCommPermission(Permission.photos);
        }else{
          checkPermission =await CheckPermissionUtil.checkCommPermission(Permission.storage);
        }
        // LogUtil.d('selectPicture-->checkPermission=${request?.toString()}');
        if(!checkPermission)return null;
        xFile = await getImageByGallery();
        LogUtils.LogUtil.d('selectPicture-->xFile=${xFile?.path}');
      }
    }
    //压缩
    if(xFile==null)return null;
    File resultFile= File(xFile?.path);
    if(((resultFile?.readAsBytesSync()?.lengthInBytes??0)/1024)>=1024){
      ImageProperties properties = await FlutterNativeImage.getImageProperties(resultFile?.path);
      resultFile = await compressFile(resultFile?.path,targetWidth: properties?.width,targetHeight: properties?.height);
    }
    return resultFile;
  }

  Future<File> compressFile(String filePath,{int percentage,int quality,int targetWidth,int targetHeight}) async {
    LogUtils.LogUtil.d('selectPicture-->压缩前,size=${File(filePath).readAsBytesSync().lengthInBytes/1024}');
    File compressedFile = await FlutterNativeImage.compressImage(filePath,percentage: percentage??70, quality: quality??70,
        targetWidth: targetWidth??0, targetHeight: targetHeight??0);
    LogUtils.LogUtil.d('selectPicture-->压缩后,size=${compressedFile.readAsBytesSync().lengthInBytes/1024}');
    return compressedFile;
  }

  Future<File> getFile({Uint8List tempFile,String fileName}) async {
    if (tempFile != null) {
      final tempDir = await getTemporaryDirectory();

      final Directory _imageDirectory = await new Directory('${tempDir.path}/file/').create(recursive: true);
      String path = _imageDirectory.path;
      //获得一个uuud码用于给图片命名
      final String uuid = '${DateTime.now().millisecondsSinceEpoch}';
      //将压缩的图片暂时存入应用缓存目录
      File imageFile = new File('${path}originalImage_$uuid.png')..writeAsBytesSync(tempFile);

      // final tempDir = await getApplicationDocumentsDirectory();
      // final file = await new File('${tempDir.path}/$fileName').create();
      // file.writeAsBytesSync(tempFile);
      return imageFile;
    }
    return null;
  }

  // 获取相册文件
  Future<XFile> getImageByGallery({
    double maxWidth,
    double maxHeight,
    int imageQuality,
  })  async{
    XFile image = await _picker.pickImage(
      source: ImageSource.gallery,
      maxWidth: maxWidth,
      maxHeight: maxHeight,
      imageQuality: imageQuality,
    );
    LogUtil.d('selectPicture-->image=${image?.path}');
    return image;
  }
  // 获取相册多文件
  Future<List<XFile>> getMultiImageByGallery({
    ImageSource source,
    double maxWidth,
    double maxHeight,
    int imageQuality,
  })  async{
    List<XFile> images = await _picker.pickMultiImage(
      maxWidth: maxWidth,
      maxHeight: maxHeight,
      imageQuality: imageQuality,
    );
    return images;
  }
  // 获取拍照文件
   Future<XFile> getImageByCamera({
    int maxSize,
  })  async{
    XFile xFile = await _picker.pickImage(
        source: ImageSource.camera,
      preferredCameraDevice: CameraDevice.rear,);
    return xFile;
  }
  // 录制视频后获取录像文件
   Future<XFile> getVideoByCameraRecord({
    CameraDevice preferredCameraDevice,
    Duration maxDuration
  })  async{
    bool checkPermission =await CheckPermissionUtil.checkCommPermission(Permission.camera);
    if(!checkPermission)return null;
    XFile video = await _picker.pickVideo(
        source: ImageSource.camera,
      maxDuration: maxDuration??Duration(milliseconds: 1000),
      preferredCameraDevice: preferredCameraDevice??CameraDevice.rear
    );
    return video;
  }
  // 从相册获取录像文件
   Future<XFile> getVideoByGallery({Duration maxDuration})  async{
    XFile video = await _picker.pickVideo(
      source: ImageSource.gallery,
      maxDuration: maxDuration??Duration(milliseconds: 1000),
    );
    return video;
  }
}
